/*
 * Copyright (C) 2013 Peng fei Pan <sky@xiaopan.me>
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.dl7.player.utils;

import ohos.app.Context;
import ohos.app.Environment;
import ohos.data.usage.DataUsage;
import ohos.data.usage.MountState;
import ohos.data.usage.StatVfs;
import java.io.File;

/**
 * SD卡工具箱
 */
public class SDCardUtils {
    /**
     * 获取SD卡的状态
     * @return
     */
    public static MountState getState() {
        return DataUsage.getDiskMountedStatus();
    }


    /**
     * SD卡是否可用
     *
     * @return 只有当SD卡已经安装并且准备好了才返回true
     */
    public static boolean isAvailable() {
        return getState().equals(MountState.DISK_MOUNTED);
    }


    /**
     * 获取SD卡的根目录
     *
     * @return null：不存在SD卡
     */
    public static File getRootDirectory(Context context) {
        File externalFilesDir = context.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS);
        return isAvailable() ? externalFilesDir : null;
    }


    /**
     * 获取SD卡的根路径
     *
     * @return null：不存在SD卡
     */
    public static String getRootPath(Context context) {
        File rootDirectory = getRootDirectory(context);
        return rootDirectory != null ? rootDirectory.getPath() : null;
    }

    /**
     * 获取sd卡路径
     *
     * @return Stringpath
     */
    public static String getSDPath(Context context) {
        File sdDir = null;
        boolean sdCardExist = DataUsage.getDiskMountedStatus()
                .equals(MountState.DISK_MOUNTED);   //判断sd卡是否存在
        if (sdCardExist) {
            sdDir = context.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS); //获取跟目录
        }
        return sdDir.toString();
    }

    /**
     * 获取空闲的空间大小
     * @param path  文件路径
     * @return  空间大小
     */
    public static long getFreeSpaceBytes(final String path) {
        final StatVfs statVfs = new StatVfs(path);
        long freeSpaceBytes = statVfs.getAvailableSpace();
        return freeSpaceBytes;
    }

}
